<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <span style="color: red;">
          "说明：1、本表财政支出结余应为0，非财政收入中技术服务收入、成果转化收入、科研副产品收入均填报真实测算收入，因预算上报为平衡预算，可与预算收入明细表中的预算收入不一致，本表测算产生的收支结余仅作为后续管理参考依据；
          2、填报举例：维修费：如维修大门3.5万，测算内容：大门维修；测算依据：说明3.5万金额是如何测算出来的；
          3、各单位科室只需测算基本公用经费，与非财政收入相关的经费支出不按科室测算，即各科室（基本）=财政基本+非财政基本；
          4、各项支出科目可按报账规范要求进行具体测算 。"
        </span>
        <span style="color: red;">单位：万元
        </span>
        <a-row>
          <a-col :span="24">
            <a-form-model-item label="科室名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="ksmc">
              <a-input v-model="model.ksmc" placeholder="请输入科室名称"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="年度" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="nd">
              <j-dict-select-tag type="list" v-model="model.nd" dictCode="year" placeholder="请选择年度"
                @change="handleYearChange" />
            </a-form-model-item>
          </a-col>

          <!-- 全部费用项目直接列出，每个项目包含三个输入框 -->
          <a-col :span="24" v-for="(expense, index) in expenseOptions" :key="expense.prop" style="margin-bottom: 16px;">
            <div style="border: 1px solid #e8e8e8; border-radius: 4px; padding: 12px;">
              <div style="font-weight: 600; margin-bottom: 8px; color: #1890ff;">
                {{ index + 1 }}. {{ expense.label }}
              </div>
              <a-row :gutter="16">
                <!-- 金额输入 -->
                <a-col :span="6">
                  <a-form-model-item label="金额" :labelCol="{ xs: { span: 8 }, sm: { span: 8 } }"
                    :wrapperCol="{ xs: { span: 16 }, sm: { span: 16 } }" :prop="`expenses.${expense.prop}.amount`"
                    :rules="validatorRules.amount">
                    <a-input v-model.number="model.expenses[expense.prop].amount" placeholder="输入金额" type="number"
                      style="width: 100%;" />
                  </a-form-model-item>
                </a-col>

                <!-- 测算内容输入 -->
                <a-col :span="9">
                  <a-form-model-item label="测算内容" :labelCol="{ xs: { span: 6 }, sm: { span: 6 } }"
                    :wrapperCol="{ xs: { span: 18 }, sm: { span: 18 } }" :prop="`expenses.${expense.prop}.content`"
                    :rules="validatorRules.content">
                    <a-input v-model="model.expenses[expense.prop].content" placeholder="说明具体用途" style="width: 100%;" />
                  </a-form-model-item>
                </a-col>

                <!-- 测算依据输入 -->
                <a-col :span="9">
                  <a-form-model-item label="测算依据" :labelCol="{ xs: { span: 6 }, sm: { span: 6 } }"
                    :wrapperCol="{ xs: { span: 18 }, sm: { span: 18 } }" :prop="`expenses.${expense.prop}.basis`"
                    :rules="validatorRules.basis">
                    <a-input v-model="model.expenses[expense.prop].basis" placeholder="说明测算逻辑" style="width: 100%;" />
                  </a-form-model-item>
                </a-col>
              </a-row>
            </div>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>
import { mapState } from 'vuex'
import { httpAction } from '@/api/manage'

export default {
  name: 'CwKsForm',
  components: {},
  props: {
    disabled: {
      type: Boolean,
      default: false,
      required: false
    }
  },
  data() {
    // 全部费用项目列表（完整保留原所有项目）
    const expenseOptions = [
      { label: '办公费', prop: 'bgf' },
      { label: '印刷费', prop: 'ys' },
      { label: '手续费', prop: 'sx' },
      { label: '水费', prop: 'sf' },
      { label: '电费', prop: 'df' },
      { label: '邮电费', prop: 'yd' },
      { label: '取暖费', prop: 'qn' },
      { label: '物业管理费', prop: 'wy' },
      { label: '差旅费', prop: 'cl' },
      { label: '因公出国（境）费用', prop: 'cg' },
      { label: '维修（护）费', prop: 'wxf' },
      { label: '租赁费', prop: 'zl' },
      { label: '会议费', prop: 'hy' },
      { label: '培训费', prop: 'px' },
      { label: '公务接待费', prop: 'gwjd' },
      { label: '专用材料费', prop: 'zycl' },
      { label: '被装购置费', prop: 'bz' },
      { label: '专用燃料费', prop: 'zyll' },
      { label: '劳务费', prop: 'lw' },
      { label: '委托业务费', prop: 'wt' },
      { label: '工会经费', prop: 'gh' },
      { label: '公务用车运行维护费', prop: 'gwc' },
      { label: '其他交通费用', prop: 'qtjtfy' },
      { label: '税金及附加费用', prop: 'sj' },
      { label: '其他商品和服务支出', prop: 'qtsp' },
      { label: '房屋建筑物购建', prop: 'fw' },
      { label: '办公设备购置', prop: 'bg' },
      { label: '专用设备购置', prop: 'zy' },
      { label: '基础设施建设', prop: 'jc' },
      { label: '大型修缮', prop: 'dx' },
      { label: '信息网络及软件购置更新', prop: 'xx' },
      { label: '物资储备', prop: 'wz' },
      { label: '土地补偿', prop: 'td' },
      { label: '安置补助', prop: 'az' },
      { label: '地上附着物和青苗补偿', prop: 'ds' },
      { label: '拆迁补偿', prop: 'cq' },
      { label: '公务用车购置', prop: 'gw' },
      { label: '其他交通工具购置', prop: 'qtjt' },
      { label: '文物和陈列品购置', prop: 'ww' },
      { label: '无形资产购置', prop: 'wx' },
      { label: '其他资本性支出', prop: 'qt' }
    ]

    // 初始化每个费用项目的输入数据结构
    const initExpenses = {}
    expenseOptions.forEach(expense => {
      initExpenses[expense.prop] = {
        amount: null,
        content: '',
        basis: ''
      }
    })

    return {
      model: {
        nd: '',
        ksmc: '',
        expenses: initExpenses // 存储所有费用项目的输入数据
      },
      expenseOptions,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      confirmLoading: false,
      validatorRules: {
        ksmc: [{ required: true, message: '请输入科室名称', trigger: 'blur' }],
        nd: [{ required: true, message: '请选择年度', trigger: 'change' }],
        // 单个费用项目的验证规则
        amount: [
          { required: false, message: '请输入金额', trigger: 'blur' },
          { type: 'number', message: '金额必须为数字', trigger: 'change', transform: (value) => Number(value) }
        ],
        content: [{ required: false, message: '请输入测算内容', trigger: 'blur' }],
        basis: [{ required: false, message: '请输入测算依据', trigger: 'blur' }]
      },
      url: {
        add: "/cw/cwKs/add",
        edit: "/cw/cwKs/edit",
        queryById: "/cw/cwKs/queryById"
      },
      isManualChange: false
    }
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
    ...mapState({ globalYear: state => state.app.globalYear })
  },
  watch: {
    globalYear(newVal) {
      if (!this.isManualChange && newVal) {
        this.model.nd = newVal;
      }
    },
    'model.nd'(newVal, oldVal) {
      if (oldVal && newVal !== this.globalYear) {
        this.isManualChange = true;
      }
    }
  },
  created() {
    if (this.globalYear) {
      this.model.nd = this.globalYear;
    }
    this.modelDefault = JSON.parse(JSON.stringify(this.model));
  },
  methods: {
    handleYearChange(val) {
      console.log('选择的年度:', val);
    },

    // 准备提交数据：拼接成 "金额,测算内容,测算依据" 格式
    prepareSubmitData() {
      const submitData = { ...this.model };
      // 遍历所有费用项目，拼接格式
      this.expenseOptions.forEach(expense => {
        const item = submitData.expenses[expense.prop];
        const amount = item.amount || 0;
        const content = item.content || '未填写';
        const basis = item.basis || '未填写';
        // 按要求格式存储到对应字段
        submitData[expense.prop] = `${amount},${content},${basis}`;
      });
      // 删除临时的 expenses 字段，不需要提交
      delete submitData.expenses;
      return submitData;
    },

    add() {
      this.edit(this.modelDefault);
    },

    edit(record) {
      // 编辑时，将拼接格式的数据拆分回输入结构
      const model = Object.assign({}, record);
      const initExpenses = {};
      this.expenseOptions.forEach(expense => {
        const value = model[expense.prop] || '0,未填写,未填写';
        const [amount, content, basis] = value.split(',');
        initExpenses[expense.prop] = {
          amount: Number(amount) || null,
          content: content || '',
          basis: basis || ''
        };
        // 删除原拼接字段
        delete model[expense.prop];
      });
      model.expenses = initExpenses;
      this.model = model;
    },

    submitForm() {
      const that = this;
      this.$refs.form.validate(valid => {
        if (valid) {
          const submitData = this.prepareSubmitData();
          that.confirmLoading = true;
          let httpurl = '';
          let method = '';
          if (!submitData.id) {
            httpurl += this.url.add;
            method = 'post';
          } else {
            httpurl += this.url.edit;
            method = 'put';
          }
          httpAction(httpurl, submitData, method).then((res) => {
            if (res.success) {
              that.$message.success(res.message);
              that.$emit('ok');
            } else {
              that.$message.warning(res.message);
            }
          }).finally(() => {
            that.confirmLoading = false;
          })
        } else {
          this.$message.error('表单填写有误，请检查后重新提交')
        }
      })
    },
  }
}
</script>